package cn.rengy.isql;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import java.util.List;
/**
 * 未命名参数
 * 可以根据SqlParameterSource拼接多个?
 *
 */
@Getter
@Setter
@AllArgsConstructor
public class UnNamedParameterHolder implements ParameterHolder {

	/**参数在SQL字符串中的位置**/
	private final int index;
	
	/**参数在SQL中出现顺序从0开始**/
	private final int paramIndex;
	
	@Override
	public String parse(SqlParameterSource paramSource) {
		if(paramSource!=null) {
			if(paramSource instanceof UnNamedSqlParameterSource) {
				UnNamedSqlParameterSource ps=(UnNamedSqlParameterSource)paramSource;
				Object value=ps.getValue(paramIndex);
				StringBuilder sb=new StringBuilder();
				SqlParser.appendParameters(sb, value);
				return sb.toString();
			}else {
				String[] names=paramSource.getParameterNames();
				if(names!=null) {
					if(paramIndex<names.length){
						String paramName=names[paramIndex];
						Object value=paramSource.getValue(paramName);
						StringBuilder sb=new StringBuilder();
						SqlParser.appendParameters(sb, value);
						return sb.toString();
					}
				}
			}
		}
		return "?";
	}
	
	
	@Override
	public void appendValueList(List<Object> valueList, SqlParameterSource paramSource) {
		Object paramValue=null;
		if(paramSource!=null) {
			if(paramSource instanceof UnNamedSqlParameterSource) {
				UnNamedSqlParameterSource ps=(UnNamedSqlParameterSource)paramSource;
				paramValue=ps.getValue(paramIndex);
			}else {
				String[] names=paramSource.getParameterNames();
				if(names!=null) {
					if(paramIndex<names.length){
						String paramName=names[paramIndex];
						paramValue=paramSource.getValue(paramName);
					}
				}
			}
		}
		SqlParser.appendValueArray(valueList,paramValue);
	}

	@Override
	public int getStartIndex() {
		return index;
	}


	@Override
	public int getEndIndex() {
		return index+1;
	}


//	@Override
//	public String getParameterName() {
//		return String.valueOf(paramIndex);
//	}
	
}